package cn.fl.ref.contract.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alibaba.fastjson.JSONObject;

import cn.fl.framework.base.context.CurrentThreadContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.fl.ref.contract.service.IFncPrjContDetailApplyService;
import cn.fl.ref.contract.service.IFncPrjContDetailService;
import cn.fl.ref.contract.service.IFncPrjContMainApplyService;
import cn.fl.ref.contract.service.IFncPrjContMainService;
import cn.fl.ref.contract.vo.FncPrjContDetailApplyVO;
import cn.fl.ref.contract.vo.FncPrjContDetailVO;
import cn.fl.ref.contract.vo.FncPrjContMainVO;
import cn.fl.system.constant.SysLogConstant;
import cn.fl.system.service.ISysUlFilesRecService;
import cn.fl.system.service.ISysUsrService;
import cn.fl.system.vo.SysUlFilesRecVO;
import cn.fl.system.vo.SysUsrVO;
import cmm.comm.facade.framework.api.ISysDictionaryApiService;
import cmm.comm.facade.framework.dto.SysDictionaryDTO;
import cmm.comm.facade.upload.condition.SysUlFilesRecQueryCondition;
import cmm.mid.core.framework.page.DataResultVO;
import cmm.mid.core.framework.page.KeyValueVO;
import cmm.mid.core.framework.page.ListPageVO;
import cmm.mid.core.framework.page.Pager;
import cmm.web.core.framework.controller.BaseController;
import cn.cmm.base.framework.constant.BaseConstant;
import cn.cmm.base.framework.exception.BaseException;
import cn.cmm.base.framework.utils.BaseLogUtils;
import cn.cmm.base.framework.utils.CollectionUtils;
import cn.cmm.base.framework.utils.DateUtils;
import cn.cmm.base.framework.utils.StringUtils;
import fl.ref.contract.condition.FncPrjContDetailApplyQueryCondition;
import fl.ref.contract.condition.FncPrjContDetailQueryCondition;
import fl.ref.contract.constant.FncPrjContMainConstant;

/**
 * @Description: 合同管理明细表 控制层
 */
@Controller
@RequestMapping("/rfbuss/fncPrjContDetail")
public class FncPrjContDetailController extends BaseController {

	private static final Logger logger = LoggerFactory.getLogger(FncPrjContDetailController.class);

	/**
	 * FncPrjContDetail 服务层BEAN
	 */
	@Autowired
	private IFncPrjContDetailService fncPrjContDetailService;
	
	@Autowired
	private IFncPrjContMainService fncPrjContMainService;//合同服务
	@Autowired
	private IFncPrjContMainApplyService fncPrjContMainApplyService;//合同申请主表服务
	@Autowired
	private IFncPrjContDetailApplyService fncPrjContDetailApplyService;//合同申请明细表服务
	@Autowired
	private ISysUlFilesRecService sysUlFilesRecService;//附件服务
	
	@Autowired
	private ISysDictionaryApiService sysDictionaryApiService;//数据字典
	
	@Autowired
	private ISysUsrService sysUsrService;//用户服务

	/**
	 * 到列表页面
	 */
	@RequestMapping(value = "/toListPage.do", method = { RequestMethod.GET})
	public ModelAndView toListPage(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView("rfbuss/fncPrjContDetail/list");
		BaseLogUtils.info(logger, "toListPage", "跳转到列表页面.", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 到新增/修改页面
	 */
	@RequestMapping(value = "/toModifyPage.do", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView toModifyPage(HttpServletRequest request, HttpServletResponse response) {
		String id = request.getParameter("id");//合同明细ID
		String contId = request.getParameter("contId");//合同主表ID
		String fncPrjId = request.getParameter("fncPrjId");//项目编号
		ModelAndView view = new ModelAndView("rfbuss/fncPrjContDetail/fncPrjContDetailEdit");
		view.addObject("id", id);
		view.addObject("contId", contId);
		view.addObject("fncPrjId", fncPrjId);
		//获取合同状态
		String sysCd = CurrentThreadContext.getCurrentSysCd(); 
		String orgCd = CurrentThreadContext.getCurrentOrgCd();
		List<KeyValueVO> contStsList = this.fncPrjContMainService.getKvList(FncPrjContMainConstant.CONT_STS_CD, sysCd, orgCd);
		view.addObject("contStsList", contStsList);
		//查询合同明细
		if(StringUtils.isNotEmpty(id)){
			FncPrjContDetailVO ContDetailVo = this.fncPrjContDetailService.selectById(Long.valueOf(id));
			view.addObject("ContDetailVo", ContDetailVo);
        }
		view.addObject("sysDate", DateUtils.formatDateToString(new Date(), DateUtils.YYYY_MM_DD));
		view.addObject("loginUsrNm", CurrentThreadContext.getCurrentUserName());
		BaseLogUtils.info(logger, "toModifyPage", "跳转到新增/修改页面.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		return view;
	}

	/**
	 * 初始化列表
	 */
	@RequestMapping(value = "/initList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initList(HttpServletRequest request, HttpServletResponse response) {
		String contId = request.getParameter("contId");//合同ID
		String mainId = request.getParameter("mainId");//合同ID
		String contDetailStatus=request.getParameter("contDetailStatus");//合同状态
		String isfilter=request.getParameter("isfilter");//是否过滤
		
		FncPrjContDetailQueryCondition qc = new FncPrjContDetailQueryCondition();
		if (StringUtils.isNotEmpty(contId)) {
			qc.setFncPrjContMainId(Long.parseLong(contId));
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			qc.setIsValid(BaseConstant.IS_YESNO_YES);
		}else if (StringUtils.isNotEmpty(mainId)) {
			qc.setFncPrjContMainId(Long.parseLong(mainId));
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			qc.setIsValid(BaseConstant.IS_YESNO_YES);
		}else{
			BaseLogUtils.info(logger, "initList", "查询数据完成.合同主键为空！ contId:[" + contId + "];mainId:[" + mainId+ "]", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		if(StringUtils.isNotEmpty(contDetailStatus)){//add 合同状态
			qc.setContDetailStatus(Integer.parseInt(contDetailStatus));
		}

		List<FncPrjContDetailVO> list = this.fncPrjContDetailService.searchList(qc);
	
		//isfilter 过滤未审核通过的合同明细,(0,4)
		if("1".equals(isfilter)){
			for(int i=0;i<list.size();i++){
				FncPrjContDetailVO detailVo=list.get(i);
				if(detailVo!=null){
					if(detailVo.getContDetailStatus()!=null){
						if("0".equals(detailVo.getContDetailStatus().toString())|| 
								"4".equals(detailVo.getContDetailStatus().toString())){
						}else{
							list.remove(detailVo);
							i--;
						}
					}
				}
			}
		}//end isfilter
		if(!CollectionUtils.isNotEmpty(list)){
			list = new ArrayList<FncPrjContDetailVO>();
		}
		SysDictionaryDTO dictionary = null;
		String sysCd = FncPrjContMainConstant.SYS_CODE; 
		String orgCd = FncPrjContMainConstant.ORG_CODE;
		for(FncPrjContDetailVO vo : list){
			//处理合同状态
			if(StringUtils.isEmpty(vo.getContDetailStatus())){
				vo.setContDetailStatus(BaseConstant.IS_YESNO_NO);
			}
			dictionary = sysDictionaryApiService.getCode(sysCd, orgCd, FncPrjContMainConstant.CONT_DETAIL_STS_CD, vo.getContDetailStatus().toString());
			if(null != dictionary){
				vo.setContDetailStatusNm(dictionary.getCodeNm());
			}
			
			//获取相应附件列表
			if(null != vo.getId()){
				SysUlFilesRecQueryCondition condition = new SysUlFilesRecQueryCondition();
				condition.setCfgCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGCD);//REF001-再融资模块
				condition.setTabNm(FncPrjContMainConstant.FNC_PRJ_CONT_DETAIL_TABNM);
				condition.setCfgDtlCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_20);
				condition.setPkId(vo.getId().toString());
				condition.setSysCd(sysCd);//系统代码-必须条件
				List<SysUlFilesRecVO> filesList = this.sysUlFilesRecService.searchList(condition);
				if(CollectionUtils.isNotEmpty(filesList) && filesList.size()>0){
					vo.setFilesList(filesList);
				}
				BaseLogUtils.info(logger, "initList", "查询合同附件列表. DATA:" + JSONObject.toJSONString(filesList), CurrentThreadContext.getCurrentUserName());
			}
		}
		
		ListPageVO<FncPrjContDetailVO> listPage = new ListPageVO<FncPrjContDetailVO>(list, list.size());
		BaseLogUtils.info(logger, "initList", "查询数据完成. DATA:" + JSONObject.toJSONString(qc), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}

	/**
	 * 删除数据
	 */
	@RequestMapping(value = "/removeById.do", method = {RequestMethod.POST })
	@ResponseBody
	public DataResultVO removeById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		String mainId = request.getParameter("mainId");
		String applyId = request.getParameter("applyId");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_DELETE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			return result;
		}
		try {
			//根据合同申请主表applyId获取合同申请明细表
			boolean success = this.fncPrjContDetailService.removeById(Long.valueOf(id));
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "removeById", "删除失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
				return result;
			}else{
				Long contNum = 0L;
				FncPrjContMainVO entity = new FncPrjContMainVO();
				if(StringUtils.isNotEmpty(mainId)){
					Long contId = Long.parseLong(mainId);
					FncPrjContMainVO contMainVo = this.fncPrjContMainService.selectById(contId);
					if(null != contMainVo){
						contNum = contMainVo.getContNum();
						entity.setId(contId);
						entity.setContNum(contNum - 1);
						entity.setMdfTm(new Date());
						entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
						boolean success2 = this.fncPrjContMainService.modify(entity);
						if(!success2){
							result.setSuccess(BaseConstant.IS_YESNO_NO);
							result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
							BaseLogUtils.info(logger, "removeById", "修改合同主表合同份数失败.[mainId="+mainId+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
						}
					}
				}
			}
			//判断是否需要删除合同申请明细表数据
			if(StringUtils.isNotEmpty(applyId)){
				//根据合同申请applyId获取此流程对应的合同明细信息
				List<FncPrjContDetailApplyVO> applyList=new ArrayList<FncPrjContDetailApplyVO>(); 
				if (StringUtils.isNotEmpty(applyId)) {
					FncPrjContDetailApplyQueryCondition applyQc = new FncPrjContDetailApplyQueryCondition();
					applyQc.setFncPrjContMainApplyId(Long.parseLong(applyId));
					applyList=fncPrjContDetailApplyService.searchList(applyQc);
					for(FncPrjContDetailApplyVO detailVo:applyList){
						if(detailVo.getFncPrjContDetailId()!=null ){
							if(id.equals(detailVo.getFncPrjContDetailId().toString())){
								boolean successd = this.fncPrjContDetailApplyService.removeById(detailVo.getId());
								if(!successd){
									result.setSuccess(BaseConstant.IS_YESNO_NO);
									result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
									BaseLogUtils.info(logger, "removeById", "删除失败.[id="+detailVo.getId()+"]", CurrentThreadContext.getCurrentUserName());
									return result;
								}
							}
						}
					}
				}//end
			}//end 合同申请明细表
			BaseLogUtils.info(logger, "removeById", "删除数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "removeById", "删除数据失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}

		return result;
	}

	/**
	 * 得到一条记录
	 * 
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/getById.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object getById(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_OPERATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "getById", "获取数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		
		try {
			FncPrjContDetailVO vo = this.fncPrjContDetailService.selectById(Long.valueOf(id));
			if(null == vo){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_QUERY_DATA_IS_EMPTY);
				BaseLogUtils.info(logger, "getById", "获取数据,数据不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			}
			result.setData(vo);
			BaseLogUtils.info(logger, "getById", "获取数据.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
		}catch(BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}catch(Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "getById", "获取失败.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}

	/**
	 * 新增/修改合同信息表
	 */
	@RequestMapping(value = "/saveContract.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object saveContract(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String contId = request.getParameter("contId");//合同主表ID
		String detailId = request.getParameter("id");//合同明细表ID
		String fncPrjId = request.getParameter("fncPrjId");//项目编号
		String contDetailNm = request.getParameter("contDetailNm");
		String contDetailStatus = request.getParameter("contDetailStatus");
		String contDetailRemark = request.getParameter("contDetailRemark");
		String mainContractNo = request.getParameter("mainContractNo");//主合同编号
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_ADD_SUCC);
		Long id = null;
		Long mainId = null;
		Long contNum = 0L;
		FncPrjContDetailVO entity = null;
		FncPrjContMainVO entity2 = null;
		try {
			entity = new FncPrjContDetailVO();
			entity.setContDetailNm(contDetailNm);
			entity.setContDetailRemark(contDetailRemark);
			entity.setMainContractNo(mainContractNo);//主合同编号
			if(StringUtils.isNotEmpty(contDetailStatus)){
				entity.setContDetailStatus(Integer.parseInt(contDetailStatus));
			}
			
			//判断合同主表是否存在
			if(StringUtils.isNotEmpty(contId)){
				mainId = Long.parseLong(contId);
				entity.setFncPrjContMainId(mainId);
				FncPrjContMainVO contMainVo = this.fncPrjContMainService.selectById(mainId);
				if(null != contMainVo){
					contNum = contMainVo.getContNum();
				}
			}else{
				entity2 = new FncPrjContMainVO();
				entity2.setFncPrjId(fncPrjId);
				entity2.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				mainId = this.fncPrjContMainService.add(entity2);
				entity.setFncPrjContMainId(mainId);
			}
			
			//判断是修改还是新增-合同明细表
			if(StringUtils.isNotEmpty(detailId)){
				id = Long.parseLong(detailId);
				entity.setId(id);
				entity.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
				boolean success = this.fncPrjContDetailService.modify(entity);
				if(!success){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
					BaseLogUtils.info(logger, "saveContract", "修改合同明细数据失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				}else{
					result.setInfo(SysLogConstant.LOG_CMM_UPDATE_SUCC);
				}
			}else{
				entity.setCrtUsrId(CurrentThreadContext.getCurrentUserId());
				id = this.fncPrjContDetailService.add(entity);
				//修改合同主表中的合同份数+1
				if(null != id){
					entity2 = new FncPrjContMainVO();
					entity2.setId(mainId);
					entity2.setContNum(contNum + 1);
					entity2.setMdfUsrId(CurrentThreadContext.getCurrentUserId());
					boolean success = this.fncPrjContMainService.modify(entity2);
					if(!success){
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
						BaseLogUtils.info(logger, "saveContract", "修改合同主表合同份数失败.[mainId="+mainId+"] DATA:" + JSONObject.toJSONString(entity2), CurrentThreadContext.getCurrentUserName());
					}
				}
			}
			result.setData(id);//将合同明细ID传到页面-用以保存文件使用
			result.setId(mainId);//将主合同ID传到页面-以便发起审核流程使用
			BaseLogUtils.info(logger, "saveContract", "新增/修改合同数据.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "saveContract", "新增/修改合同数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "saveContract", "新增/修改合同数据失败.DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}

		return result;
	}

	/**
	 * 修改
	 */
	@RequestMapping(value = "/modify.do", method = { RequestMethod.POST })
	@ResponseBody
	public Object modify(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String id = request.getParameter("id");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_CMM_UPDATE_SUCC);
		if(StringUtils.isEmpty(id)){
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_DATA_PK_IS_EMPTY);
			BaseLogUtils.info(logger, "modify", "修改数据,主键不存在.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
			return result;
		}
		FncPrjContDetailVO entity = null;
		try {
			entity = new FncPrjContDetailVO();
			entity.setId(Long.valueOf(id));
			//TODO ADD PARAM
			boolean success = this.fncPrjContDetailService.modify(entity);
			if(!success){
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.info(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
				return result;
			}
			BaseLogUtils.info(logger, "modify", "修改成功.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName());
		}catch (BaseException ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(ex.getMessage());
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}catch (Exception ex) {
			result.setSuccess(BaseConstant.IS_YESNO_NO);
			result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
			BaseLogUtils.error(logger, "modify", "修改失败.[id="+id+"] DATA:" + JSONObject.toJSONString(entity), CurrentThreadContext.getCurrentUserName(), ex);
		}
		return result;
	}
	
	/**
	 * 保存附件信息
	 */
	@RequestMapping(value = "/uploadAttchment.do", method = { RequestMethod.POST,RequestMethod.GET })
	@ResponseBody
	public Object uploadAttchment(HttpServletRequest request, HttpServletResponse response) throws BaseException {
		String attchmnt = request.getParameter("docArray");
		String id = request.getParameter("pkId");
		String flag = request.getParameter("flag");
		DataResultVO result = new DataResultVO(BaseConstant.IS_YESNO_YES, SysLogConstant.LOG_FILE_UPLOAD_SUCC);
		if(StringUtils.isNotEmpty(attchmnt) && StringUtils.isNotEmpty(id)){
			//上传解析
			try{
				Boolean isDel = false;
				String fileRem = ""; //文件说明
				String cfgDtlCd = ""; //配置子编号
				String tabNm = ""; //数据表名
				String cfgCd = FncPrjContMainConstant.FNC_PRJ_CONT_CFGCD; //配置编号：REF001
				String cfgOrgCd = FncPrjContMainConstant.FNC_PRJ_CONT_CFGORG; //组织架构代码：0000
				//判断标识确定文件配置编码
				if (StringUtils.isNotEmpty(flag)) {
					if("hkb".equals(flag)){//还款表附件
						isDel = true;
						fileRem = "还款表";
						tabNm = FncPrjContMainConstant.FNC_PRJ_PAY_PLAN_TABNM; //还款计划表
						cfgDtlCd = FncPrjContMainConstant.FNC_PRJ_PAY_CFGDTLCD_10;
					}else if("htfj".equals(flag)){//合同明细附件
						fileRem = "合同明细附件";
						tabNm = FncPrjContMainConstant.FNC_PRJ_CONT_DETAIL_TABNM; //合同管理明细表
						cfgDtlCd = FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_20;
					}else if("htfyj".equals(flag)){//合同复印件
						fileRem = "合同复印件";
						tabNm = FncPrjContMainConstant.FNC_PRJ_CONT_MAIN_TABNM; //合同管理主表
						//根据业务主键判断
						String str=id.substring(6,9);
						if("728".equals(str)){//合同管理申请主表
							tabNm = FncPrjContMainConstant.FNC_PRJ_CONT_MAIN_APPLY_TABNM;
						}
						cfgDtlCd = FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_40;
					}else if("gzdzb".equals(flag)){//盖章电子版
						fileRem = "盖章电子版附件";
						tabNm = FncPrjContMainConstant.FNC_PRJ_CONT_MAIN_APPLY_TABNM; //合同管理明细表
						cfgDtlCd = FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_50;
					}else if("zhb".equals(flag)){//最终版
						fileRem = "最终版";
						tabNm = FncPrjContMainConstant.FNC_PRJ_CONT_DETAIL_TABNM; //合同管理明细表
						cfgDtlCd = FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_60;
					}
					else{
						result.setSuccess(BaseConstant.IS_YESNO_NO);
						result.setInfo("文件上传标识不能识别！不能上传附件!");
						BaseLogUtils.info(logger, "uploadAttchment", "文件上传标识不能识别.不能上传附件.[flag="+flag+"]", CurrentThreadContext.getCurrentUserName());
						return result;
					}
				}else{
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("文件上传标识为空！不能上传附件!");
					BaseLogUtils.info(logger, "uploadAttchment", "文件上传标识为空.不能上传附件.[flag="+flag+"]", CurrentThreadContext.getCurrentUserName());
					return result;
				}
				Boolean attchmntPass = this.sysUlFilesRecService.addAttchmnt(String.valueOf(id), attchmnt, cfgCd, cfgDtlCd, tabNm, fileRem, null, null, isDel, cfgOrgCd);
				if(null == attchmntPass || attchmntPass == false){
					result.setSuccess(BaseConstant.IS_YESNO_NO);
					result.setInfo("再融资模块附件上传失败!");
					BaseLogUtils.info(logger, "uploadAttchment", "再融资模块附件上传失败1.[id="+id+"]", CurrentThreadContext.getCurrentUserName());
				}
				result.setData(id);//设置附件关联主键
			}catch (BaseException ex) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(ex.getMessage());
				BaseLogUtils.error(logger, "uploadAttchment", "再融资模块附件上传失败2.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
			}catch (Exception ex) {
				result.setSuccess(BaseConstant.IS_YESNO_NO);
				result.setInfo(SysLogConstant.LOG_CMM_SYS_ERROR);
				BaseLogUtils.error(logger, "uploadAttchment", "再融资模块附件上传失败3.[id="+id+"]", CurrentThreadContext.getCurrentUserName(), ex);
			}
		}
		return result;
	}
	
	/**
	 * 初始化文件列表
	 */
	@RequestMapping(value = "/initFilesList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initFilesList(HttpServletRequest request, HttpServletResponse response) {
		String currentPage = request.getParameter("page");
		String pageSize = request.getParameter("pagesize");
		String pkId = request.getParameter("pkId");
		String tabNm = request.getParameter("tabNm");
		String pkIdList = request.getParameter("pkIdList");//主键List
		String cfgDtlCd =  request.getParameter("cfgDtlCd");
		String cfgCd =  request.getParameter("cfgCd");
		Pager page = new Pager();
		if (StringUtils.isNotEmpty(currentPage)) {
			page.setCurrentPage(Integer.parseInt(currentPage));
		}

		if (StringUtils.isNotEmpty(pageSize)) {
			page.setEveryPage(Integer.parseInt(pageSize));
		}

		SysUlFilesRecQueryCondition qc = new SysUlFilesRecQueryCondition();
		if ((StringUtils.isEmpty(pkId) && StringUtils.isEmpty(pkIdList))||StringUtils.isEmpty(tabNm)) {
			BaseLogUtils.info(logger, "initFilesList", "查询数据的文件上传信息,数据主键或数据表名为空！PKId:"+JSONObject.toJSONString(pkId), CurrentThreadContext.getCurrentUserName());
			return page;
		}
		//判断此次传参是否为主键List
		if (StringUtils.isNotEmpty(pkIdList)) {
			pkIdList = pkIdList.substring(1, pkIdList.length()-1);
		    String[] arr = pkIdList.split(", ");
		    List<String> pkList = java.util.Arrays.asList(arr);
			qc.setPkIdList(pkList);
		}else{
			qc.setPkId(pkId);
		}
		qc.setCfgDtlCd(cfgDtlCd);
		qc.setCfgCd(cfgCd);
		qc.setTabNm(tabNm);
		qc.setSysCd(CurrentThreadContext.getCurrentSysCd());//系统代码-必须条件
		page.setCondition(qc);
		
		BaseLogUtils.info(logger, "initFilesList", "查询数据的文件上传信息.DATA:"+JSONObject.toJSONString(page), CurrentThreadContext.getCurrentUserName());
		List<SysUlFilesRecVO> list = this.sysUlFilesRecService.searchList(qc);
		
		//遍历list查询文件上传者-真实姓名
		SysUsrVO usrVo = null;
		String sysCd = CurrentThreadContext.getCurrentSysCd();
		if(CollectionUtils.isNotEmpty(list) && list.size()>0){
			for(SysUlFilesRecVO vo : list){
				usrVo = this.sysUsrService.selectById(vo.getCrtUsrId(), sysCd);
				vo.setCrtUsrRlNm(usrVo.getRefRlNm());
			}
		}
		page.setResultList(list);
		page.setTotalCount(list.size());
		
		ListPageVO<SysUlFilesRecVO> listPage = new ListPageVO<SysUlFilesRecVO>(list, list.size());
		return listPage;
	}
	/**
	 * 初始化列表(根据合同申请主键获取此流程对应合同明细信息)
	 */
	@RequestMapping(value = "/initApplyList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initApplyList(HttpServletRequest request, HttpServletResponse response) {
		String contId = request.getParameter("contId");//合同ID
		String mainId = request.getParameter("mainId");//合同ID
		String applyId = request.getParameter("applyId");//合同申请applyId
		FncPrjContDetailQueryCondition qc = new FncPrjContDetailQueryCondition();
		if (StringUtils.isNotEmpty(contId)) {
			qc.setFncPrjContMainId(Long.parseLong(contId));
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			qc.setIsValid(BaseConstant.IS_YESNO_YES);
		}else if (StringUtils.isNotEmpty(mainId)) {
			qc.setFncPrjContMainId(Long.parseLong(mainId));
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			qc.setIsValid(BaseConstant.IS_YESNO_YES);
		}else{
			BaseLogUtils.info(logger, "initApplyList", "查询数据完成.合同主键为空！ contId:[" + contId + "];applyId:[" + applyId+ "]", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//根据合同申请applyId获取此流程对应的合同明细信息
		List<FncPrjContDetailVO> list = new ArrayList<FncPrjContDetailVO>() ;//合同明细list
		List<FncPrjContDetailApplyVO> applyList=new ArrayList<FncPrjContDetailApplyVO>(); 
		if (StringUtils.isNotEmpty(applyId)) {
			FncPrjContDetailApplyQueryCondition applyQc = new FncPrjContDetailApplyQueryCondition();
			applyQc.setFncPrjContMainApplyId(Long.parseLong(applyId));
			applyList=fncPrjContDetailApplyService.searchList(applyQc);
			for(FncPrjContDetailApplyVO detailVo:applyList){
				if(detailVo.getFncPrjContDetailId()!=null){
					qc.setId(detailVo.getFncPrjContDetailId());
					List<FncPrjContDetailVO> list1=fncPrjContDetailService.searchList(qc);
					list.addAll(list1);
				}
			}
		}//end
		if(!CollectionUtils.isNotEmpty(list)){
			list = new ArrayList<FncPrjContDetailVO>();
		}
		SysDictionaryDTO dictionary = null;
		String sysCd = FncPrjContMainConstant.SYS_CODE; 
		String orgCd = FncPrjContMainConstant.ORG_CODE;
		for(FncPrjContDetailVO vo : list){
			//处理合同状态
			if(StringUtils.isEmpty(vo.getContDetailStatus())){
				vo.setContDetailStatus(BaseConstant.IS_YESNO_NO);
			}
			dictionary = sysDictionaryApiService.getCode(sysCd, orgCd, FncPrjContMainConstant.CONT_STS_CD, vo.getContDetailStatus().toString());
			if(null != dictionary){
				vo.setContDetailStatusNm(dictionary.getCodeNm());
			}
			//获取相应附件列表
			if(null != vo.getId()){
				SysUlFilesRecQueryCondition condition = new SysUlFilesRecQueryCondition();
				condition.setCfgCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGCD);//REF001-再融资模块
				condition.setTabNm(FncPrjContMainConstant.FNC_PRJ_CONT_DETAIL_TABNM);
				condition.setCfgDtlCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_20);
				condition.setPkId(vo.getId().toString());
				condition.setSysCd(sysCd);//系统代码-必须条件
				List<SysUlFilesRecVO> filesList = this.sysUlFilesRecService.searchList(condition);
				if(CollectionUtils.isNotEmpty(filesList) && filesList.size()>0){
					vo.setFilesList(filesList);
				}
				BaseLogUtils.info(logger, "initApplyList", "查询合同附件列表. DATA:" + JSONObject.toJSONString(filesList), CurrentThreadContext.getCurrentUserName());
			}
		}
		
		ListPageVO<FncPrjContDetailVO> listPage = new ListPageVO<FncPrjContDetailVO>(list, list.size());
		BaseLogUtils.info(logger, "initApplyList", "查询数据完成. DATA:" + JSONObject.toJSONString(list), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
	/**
	 * 初始化列表 按照法审流程分组显示合同信息；
	 */
	@RequestMapping(value = "/initGridList.do", method = { RequestMethod.GET})
	@ResponseBody
	public Object initGridList(HttpServletRequest request, HttpServletResponse response) {
		String applyId = request.getParameter("applyId");//合同管理申请主表ID

		FncPrjContDetailQueryCondition qc = new FncPrjContDetailQueryCondition();
		if (StringUtils.isNotEmpty(applyId)) {
			qc.setFncPrjContMainId(Long.parseLong(applyId));
			qc.setIsDel(BaseConstant.IS_YESNO_NO);
			qc.setIsValid(BaseConstant.IS_YESNO_YES);
		}else{
			BaseLogUtils.info(logger, "initList", "查询数据完成.合同主键为空！ contId:[" + applyId + "];mainId:[" + applyId+ "]", CurrentThreadContext.getCurrentUserName());
			return null;
		}
		//根据合同申请主表id获取合同管理明细表list
		List<Map<String, Object>> prjContDetailList = fncPrjContMainApplyService.selectPrjContDetailList(Long.valueOf(applyId));
		List<Long> ids=new ArrayList<Long>();
		for (Map<String, Object> prjContDetail : prjContDetailList) {
			if(StringUtils.isNotEmpty(prjContDetail.get("FNC_PRJ_CONT_DETAIL_ID").toString())){
				ids.add(Long.parseLong(prjContDetail.get("FNC_PRJ_CONT_DETAIL_ID").toString()));
			}
		}
		List<FncPrjContDetailVO> list = new ArrayList<FncPrjContDetailVO>();
		if(ids!=null && ids.size()>0){
			list= fncPrjContDetailService.searchListByIds(ids);
		}
		//List<FncPrjContDetailVO> list = this.fncPrjContDetailService.searchList(qc);

		if(!CollectionUtils.isNotEmpty(list)){
			list = new ArrayList<FncPrjContDetailVO>();
		}
		SysDictionaryDTO dictionary = null;
		String sysCd = FncPrjContMainConstant.SYS_CODE; 
		String orgCd = FncPrjContMainConstant.ORG_CODE;
		for(FncPrjContDetailVO vo : list){
			//处理合同状态
			if(StringUtils.isEmpty(vo.getContDetailStatus())){
				vo.setContDetailStatus(BaseConstant.IS_YESNO_NO);
			}
			dictionary = sysDictionaryApiService.getCode(sysCd, orgCd, FncPrjContMainConstant.CONT_DETAIL_STS_CD, vo.getContDetailStatus().toString());
			if(null != dictionary){
				vo.setContDetailStatusNm(dictionary.getCodeNm());
			}
			//处理盖章状态
			if(StringUtils.isEmpty(vo.getStampStatus())){
				vo.setStampStatus(BaseConstant.IS_YESNO_NO);
			}
			dictionary = sysDictionaryApiService.getCode(sysCd, orgCd, FncPrjContMainConstant.STAMP_STS_CD, vo.getStampStatus().toString());
			if(null != dictionary){
				vo.setStampStatusNm(dictionary.getCodeNm());
			}
			
			//获取相应附件列表
			if(null != vo.getId()){
				SysUlFilesRecQueryCondition condition = new SysUlFilesRecQueryCondition();
				condition.setCfgCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGCD);//REF001-再融资模块
				condition.setTabNm(FncPrjContMainConstant.FNC_PRJ_CONT_DETAIL_TABNM);
				condition.setCfgDtlCd(FncPrjContMainConstant.FNC_PRJ_CONT_CFGDTLCD_20);
				condition.setPkId(vo.getId().toString());
				condition.setSysCd(sysCd);//系统代码-必须条件
				List<SysUlFilesRecVO> filesList = this.sysUlFilesRecService.searchList(condition);
				if(CollectionUtils.isNotEmpty(filesList) && filesList.size()>0){
					vo.setFilesList(filesList);
				}
				BaseLogUtils.info(logger, "initList", "查询合同附件列表. DATA:" + JSONObject.toJSONString(filesList), CurrentThreadContext.getCurrentUserName());
			}
		}
		ListPageVO<FncPrjContDetailVO> listPage = new ListPageVO<FncPrjContDetailVO>(list, list.size());
		BaseLogUtils.info(logger, "initGridList", "查询数据完成. DATA:" + JSONObject.toJSONString(applyId), CurrentThreadContext.getCurrentUserName());
		return listPage;
	}
}

